package cn.tedu.medicalmanagementsystem.base.file;

import cn.tedu.medicalmanagementsystem.base.response.JsonResult;
import cn.tedu.medicalmanagementsystem.base.response.StatusCode;
import cn.tedu.medicalmanagementsystem.escort.controller.EscortController;
import cn.tedu.medicalmanagementsystem.escort.mapper.EscortImage;
import cn.tedu.medicalmanagementsystem.escort.mapper.EscortMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/v1")
public class FileUploadController {

    @Autowired
    private EscortImage escortImage;
    @Autowired
    private EscortMapper escortMapper;

    @Value("${file.upload-dir}")
    private String uploadDir;

    @Value("${server.port}")
    private String serverPort;

    @PostMapping("/upload")
    public JsonResult uploadFile(@RequestParam("file") MultipartFile file,HttpServletRequest request) {
        if (file.isEmpty()) {
            return new JsonResult(StatusCode.OPERATION_FAILED, "文件为空");
        }

        try {
            // 创建上传目录（确保使用绝对路径）
            File dir = new File(uploadDir);
            if (!dir.exists()) {
                boolean created = dir.mkdirs();
                if (!created) {
                    return new JsonResult(StatusCode.OPERATION_FAILED, "无法创建上传目录");
                }
            }

            // 生成文件名
            String originalFilename = file.getOriginalFilename();
            String fileExt = originalFilename.substring(originalFilename.lastIndexOf("."));
            String newFilename = new SimpleDateFormat("yyyyMMdd").format(new Date()) +
                    "_" + UUID.randomUUID().toString().replace("-", "") + fileExt;

            // 保存文件（使用绝对路径）
            File dest = new File(dir, newFilename);
            file.transferTo(dest);

            // 构建完整的访问URL
            String baseUrl = "http://" + request.getServerName() + ":" + serverPort;
            String accessUrl = baseUrl + "/upload/" + newFilename;

            JsonResult result = new JsonResult(StatusCode.OPERATION_SUCCESS, "上传成功");
            result.setData(accessUrl);


            Long id = EscortController.userIdd;
            //插入数据库
            escortImage.updateImage(accessUrl, id);


            return result;

        } catch (IOException e) {
            e.printStackTrace();
            return new JsonResult(StatusCode.OPERATION_FAILED, "上传失败: " + e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(StatusCode.OPERATION_FAILED, "上传失败: " + e.getMessage());
        }
    }
//    @PostMapping("/escort/update-avatar")
//    public JsonResult updateAvatar(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
//        System.out.println("updateAvatar:222222222222"+file);
//        return JsonResult.success();
//    }
}